﻿using System;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.EventSystems;
using UnityEngine.UI;

namespace Framework.UIManager
{
    public class UIManager
    {
        private static Lazy<UIManager> _instance = new Lazy<UIManager>(() => new UIManager());

        public static UIManager Instance => _instance.Value;

        
        private Dictionary<EUILayerType, Transform> _uiRoots = new Dictionary<EUILayerType, Transform>();
        public void Initial(Transform root)
        {
            Transform uiRoot = GameObject.Find("UIRoot")?.transform;

            if (uiRoot == null)
            {
                uiRoot = InitCanvas(root);
            }
            
            CreateUIRoot(uiRoot);
        }

        private Transform InitCanvas(Transform root)
        {
            // 创建UICamera
            // GameObject uiCamera = new GameObject("UICamera", typeof(Camera));
            // uiCamera.transform.SetParent(root);


            // 创建UI节点
            GameObject uiRoot =
                new GameObject("UIRoot", typeof(Canvas), typeof(GraphicRaycaster), typeof(CanvasScaler));
            int layer = LayerMask.NameToLayer("UI");
            uiRoot.transform.SetParent(root);
            uiRoot.layer = layer;

            // 创建一个新的EventSystem实例  
            if (EventSystem.current is null)
            {
                GameObject eventSystem =
                    new GameObject("EventSystem", typeof(EventSystem), typeof(StandaloneInputModule));
                eventSystem.transform.SetParent(root);
            }
            
            
            return uiRoot.transform;
        }

        private void CreateUIRoot(Transform uiRoot)
        {
            foreach (EUILayerType uienum in Enum.GetValues(typeof(EUILayerType)))
            {
                string uirootName = Enum.GetName(typeof(EUILayerType), uienum);
                GameObject uiRootGameObject = new GameObject(uirootName, typeof(RectTransform));
                uiRootGameObject.transform.SetParent(uiRoot);
                
                RectTransform rectTransform = uiRootGameObject.gameObject.GetComponent<RectTransform>();
                rectTransform.anchorMin = new Vector2(0, 0);
                rectTransform.anchorMax = new Vector2(1, 1);
                rectTransform.offsetMin = new Vector2(0, 0);
                rectTransform.offsetMax = new Vector2(0, 0);
                
                rectTransform.localScale = new Vector3(1, 1, 1);
                
                _uiRoots[uienum] = uiRootGameObject.transform;
            }
        }
    }
}